import React, {PureComponent} from "react";
import RefreshListView, {RefreshState} from "react-native-refresh-list-view";
import {
    StyleSheet,
    TouchableOpacity,
    Dimensions,
    Image,
    View,
    ToastAndroid,
    ScrollView,
    Button,
    Text,
    TextInput,
    StatusBar,
    SafeAreaView,
    DeviceEventEmitter,
} from "react-native";
import LoginSmsScene from "./LoginSmsScene";
import ResigterScene from "./ResigterScene";
import LoginSubjectScene from "./LoginSubjectScene";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scrollview'
import EditPwdScene from "./EditPwdScene";
import {isMobile,isPhoneDigit,isSmsDigit} from "../../../widget/CommonUtils";
import define from "../../../utils/define";
import {fetchPostRequest} from "../../../api/NetworkTool";
import api from "../../../api/api";
import DeviceStorage from "../../../utils/DeviceStorage";
import method from "../../../api/method";
import Tips from "react-native-root-tips";
import {Tip} from "../../../widget/Text";
import {NavigationActions} from "react-navigation";
const {width} = Dimensions.get('window')
type Props = {
    navigation:any,
    push:boolean,
}
Tips.setDefaultOptions({
    showLoading: true,
    backgroundColor: 'gray',
    opacity: 0.95,
    textColor: 'white',
    durations:1000

    // setting image you like
    // imageLoading: require('xxxxxxxxxx'),
    // imageSuccess: require('xxxxxxxxxx'),
    // imageFail: require('xxxxxxxxxx'),
    // imageInfo: require('xxxxxxxxxx'),
    // imageWarn: require('xxxxxxxxxx'),
});
export default class LoginScene extends PureComponent<Props>{
    static navigationOptions = {
        header: null,
    };
    constructor(props){
        super(props)
        this.state = {
            phone:'',
            pwd:'',
            is_login:false,
            clear:false,
            secureTextEntry:true,
        }

    }


    render(){
        return (
            <View style={styles.container}>
                        <View style={styles.text_input}>
                            <Image style={{width:8,height:12, marginLeft:11}} source={require('../../../../res/img/login/login_phone.png')}/>
                            <TextInput keyboardType='numeric' ref={(e)=>{this._phoneTF = e;}} value={this.state.phone} onEndEditing={()=>{
                                this._onEndEditing()
                            }} onChangeText={(e)=>{this._phone_onChangeText(e)}} maxLength={11} style={{padding:0,marginLeft:7,width:(width - 69 - 69),color:'rgba(0,0,0,0.8)' ,fontSize:12,fontWeight:'200'}} placeholder='请输入您的手机号' placeholderTextColor='rgba(0,0,0,0.3)' underlineColorAndroid='transparent' />
                            {this.phone_show()}
                        </View>
                     <View style={{width:(width - 86),marginTop:11,backgroundColor:'#cccccc',height:1}}/>

                        <View style={[styles.text_input]}>
                            <Image style={{width:10,height:11,marginLeft:11,marginTop:20}} source={require('../../../../res/img/login/login_pwd.png')}/>
                            <TextInput onEndEditing={()=>{
                                this._onpwdEndEditing()
                            }} onChangeText={(e)=>{this._pwd_onChangeText(e)}} ref={(e)=>{this._pwdTF = e;}} style={{padding:0,marginTop:20,marginLeft:5,width:(width - 69 - 69),color:'rgba(0,0,0,0.8)' ,fontSize:12,fontWeight:'200'}}
                                       maxLength={15}  secureTextEntry={this.state.secureTextEntry} placeholder='请输入您的密码' placeholderTextColor='rgba(0,0,0,0.3)' underlineColorAndroid='transparent' />
                            {this.pwd_show()}
                        </View>
                         <View style={{width:(width - 86),marginTop:11,backgroundColor:'#cccccc',height:1}}/>
                        {this.login_btn()}
                        <View style={{marginTop:10,flexDirection:'row',justifyContent:'space-between'}}>
                            <TouchableOpacity onPress={()=>{this.props.navigation.navigate('EditPwdScene')}}>
                                <Text style={{color:'#666666',fontSize:11,fontWeight:'200',width:100}}>忘记密码?</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={()=>{this.props.navigation.navigate('ResigterScene',{push:this.props.push})}}>
                                <Text style={{color:'#DB3840',fontSize:11,fontWeight:'200'}}>立即注册</Text>
                            </TouchableOpacity>
                        </View>
            </View>
        )
    }
    _onEndEditing(){
        if (!isMobile(this.state.phone)) {
            Tips.showWarn('请输入有效的手机号码',{mask:true})
        }
    }
    _onpwdEndEditing(){
        if (this.state.pwd.length < 6) {
            Tips.showWarn('至少输入6位密码',{mask:true})
        }
    }
    pwd_show(){
        if (this.state.secureTextEntry){
            return <TouchableOpacity style={{width:30,paddingTop:2,height:25,marginTop:14,alignItems:'center',justifyContent:'center'}} onPress={()=>{
                this.setState({secureTextEntry:!this.state.secureTextEntry})
            }}>
                <Image style={{width:12,height:5, marginRight:11}} source={require('../../../../res/img/login/login_pwd_unshow.png')}/>
            </TouchableOpacity>
        }else {
            return <TouchableOpacity style={{width:30,paddingTop:2,height:25,marginTop:14,alignItems:'center',justifyContent:'center'}} onPress={()=>{
                this.setState({secureTextEntry:!this.state.secureTextEntry})
            }}>
                <Image style={{width:12,height:5, marginRight:11}} source={require('../../../../res/img/login/login_pwd_show.png')}/>
            </TouchableOpacity>
        }

    }
    clear_handle(){
        this.setState({phone:'',clear:false})
    }
    phone_show(){
        if (this.state.clear){
            return <TouchableOpacity onPress={()=>{
                this.clear_handle()
            }}>
                <Image style={{width:8,height:8, marginRight:11}} source={require('../../../../res/img/login/login_clear.png')}/>
            </TouchableOpacity>
        }else {
            return <View/>
        }
    }

    _phone_onChangeText(e){
        if (!isPhoneDigit(e)) {
            Tips.showWarn('请输入有效的手机号码',{mask:true})
            return
        }
        this.setState({phone:e})
        if (e.length > 0){
            this.setState({clear:true})
        }else {
            this.setState({clear:false})
        }
        if (isMobile(e) && this.state.pwd.length >= 6){
            this.setState({is_login:true})
        }else {
            this.setState({is_login:false})
        }
        this.login_btn()
    }
    _pwd_onChangeText(e){

        this.setState({pwd:e})
        if (isMobile(this.state.phone) && e.length >= 6){
            this.setState({is_login:true})
        }else {
            this.setState({is_login:false})
        }
        this.login_btn()
    }

    login_btn(){
        if (this.state.is_login){
            return <TouchableOpacity style={styles.login_btn} onPress={()=>{this.login_request()}}>
                <Text style={{color:'#FEFEFE',fontSize:14,fontWeight:'bold'}}>登录</Text>
            </TouchableOpacity>
        }else {
            return <View style={styles.un_login_btn}>
                <Text style={{color:'#FEFEFE',fontSize:14,fontWeight:'bold'}}>登录</Text>
            </View>
        }
    }

    login_request(){
        let params = {
            mobile:this.state.phone,
            password:this.state.pwd,
        }
        const {push} = this.props

        Tips.showLoading('登录中...',{mask:true})
        fetchPostRequest(api.login,method.post,params)
            .then(res =>{
                DeviceStorage.save(define.token,res.token)
                DeviceStorage.save(define.profile,res.profile)
                Tips.hide()
                Tips.showSuccess('登录成功',{mask:true})
                if(push){
                    this.props.navigation.goBack()
                }else {
                    //重置根视图，闪屏页=>主界面后销毁掉
                    const resetAction = NavigationActions.reset({
                        index: 0,
                        actions: [NavigationActions.navigate({ routeName: 'home'})]})
                    this.props.navigation.dispatch(resetAction)
                }
                DeviceEventEmitter.emit('loginIn', res.profile);
                DeviceEventEmitter.emit('loginToken', res.token);
            }).catch(err =>{
            Tips.hide()
            Tips.showFail(err,{mask:true})

        })
    }
}
const styles = StyleSheet.create({
    container:{
      backgroundColor:'white',
        height:200,
    },
    register_view:{
       width:55,
       height:25,
       borderRadius:13,
        backgroundColor:'#DB3843',
        justifyContent:'center',
        alignItems:'center',
    },
    register_text:{
        color:'white',
        fontWeight:'bold',
        fontSize:12,
    },
    text_input:{
        flexDirection:"row",
        alignItems:'center',
    },
    login_btn:{
       backgroundColor:"#DB3843",
        borderRadius:17,
        height:35,
        width:(width - 86),
        borderWidth:1,
        borderColor:'rgba(219, 56, 67, 0.3)',
        marginTop:20,
        alignItems:'center',
        justifyContent:'center',
    },
    un_login_btn:{
        backgroundColor:"#999999",
        borderRadius:17,
        height:35,
        width:(width - 86),
        borderWidth:1,
        borderColor:'rgba(122, 122, 122, 0.3)',
        marginTop:20,
        alignItems:'center',
        justifyContent:'center',
    },
})